from typing import List, Optional


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # 储存 上一个节点和当前节点
        prev, curr = None, head
        while curr :
            # 储存下一个节点
            next = curr.next
            # 当前节点的下一个节点指向上一个节点
            curr.next = prev
            # 逆序节点储存修改后的当前节点
            prev = curr
            # 还原当前节点
            curr = next
        return prev

if __name__ == '__main__':
    node1 = ListNode(1)
    node2 = ListNode(2)
    node3 = ListNode(3)

    node1.next = node2
    node2.next = node3

    solution = Solution()
    node = solution.reverseList(node1)

    while node:
        print(node.val)
        node = node.next
